package com.daocao.support.config.security.service;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.daocao.common.domain.vo.LoginUserVO;
//import com.daocao.common.domain.entity.UmsMenu;
import com.daocao.common.domain.entity.UmsRole;
import com.daocao.common.domain.entity.UmsSysUser;
//import com.daocao.common.mapper.UmsMenuMapper;
import com.daocao.common.mapper.UmsSysUserMapper;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SysUserDetailsService implements UserDetailsService{

    @Autowired
    private UmsSysUserMapper sysUserMapper;

    //@Autowired
    //private UmsMenuMapper umsMenuMapper;
    /**
     * 实现方法，在此方法中根据用户名查询用户
     * 账号：用户名，手机号，邮箱，通过正则表达式判断账号类型
     */
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        // TODO 验证账号类型
        //int accountType = 0;
        UmsSysUser sysUser = sysUserMapper.selectUserByUserName(account);
        log.info("sysUser=======>{}", sysUser);
        //权限查询是根据角色查询的，首先获取所有的角色id
        if(ObjectUtil.isNotNull(sysUser)){
            List<UmsRole> roleList = sysUser.getRoleList();
            List<Long> roleIds = roleList.stream().map(UmsRole::getRoleId).collect(Collectors.toList());
            log.info("角色ID===========>{}", roleIds);
            //查询所有的菜单
            //List<UmsMenu> menuList = umsMenuMapper.selectByRoleIds(roleIds);
            // 获取list中的权限字段
            //List<String> perms = menuList.stream().map(UmsMenu::getPerms).collect(Collectors.toList());
            //log.info("权限=========>{}", perms);
            //sysUser.setPerms(perms);
        }
        //根据角色查询权限 menu
        LoginUserVO loginUserVO = new LoginUserVO();
        loginUserVO.setSysUser(sysUser);
        loginUserVO.setId(sysUser.getId());
        return loginUserVO;
    }

}
